import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_bsbdj/bean/ToDayVideo.dart';
import 'package:flutter_bsbdj/utils/constant.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'package:flutter_bsbdj/bean/video_type.dart';
import 'package:cached_network_image/cached_network_image.dart';

class TodayVideoPager extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return VideoWidget();
  }
}

class VideoWidget extends State<TodayVideoPager> {
  List<Result> _results;
  VideoPlayerController _videoPlayerController;
  ChewieController _chewieController;
  bool loading = true;
  int playId;
  ScrollController _scrollController = ScrollController();
  int videoType = 0;
  String videoPath = "https://api.apiopen.top/todayVideo";
  List<TypeItem> _typeItems;
  var _dataList = {};

  Constant _constant;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener(() {
      if (_videoPlayerController != null) {
        if (_videoPlayerController.value.isPlaying) {
          _videoPlayerController.pause();
        }
      }
    });
    _getVideoType();
    _getTodayVideo();
    _constant=Constant.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("今日视频"),
        elevation: 0,
      ),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              height: 1,
              color: Colors.grey,
            ),
            Container(
              height: 50,
              child: Row(
                children: <Widget>[
                  _videoType("推荐", 0, 0),
                  Expanded(
                    child: ListView.builder(
                      padding: EdgeInsets.only(top: 0),
                      itemCount: _typeItems == null ? 0 : _typeItems.length,
                      itemBuilder: (content, index) {
                        TypeItem item = _typeItems[index];
                        return _videoType(item.data.title.replaceAll("#", ""),
                            index + 1, item.data.id);
                      },
                      scrollDirection: Axis.horizontal,
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                child: loading
                    ? Container(
                        alignment: Alignment.center,
                        child: Container(
                          width: 30,
                          height: 30,
                          margin: EdgeInsets.all(5),
                          child: CircularProgressIndicator(),
                        ),
                      )
                    : _results == null
                        ? Center(
                            child: GestureDetector(
                              child: Text("数据获取失败！点击刷新"),
                              onTap: () {
                                _getTodayVideo();
                              },
                            ),
                          )
                        : Container(
                            child: RefreshIndicator(
                                child: ListView.builder(
                                  itemCount: _results.length,
                                  itemBuilder: (content, index) {
                                    return _todayItem(_results[index]);
                                  },
                                  controller: _scrollController,
                                ),
                                onRefresh: _refresh),
                          ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  //视频分类
  Widget _videoType(String name, int type, int id) {
    return GestureDetector(
      child: Container(
        width: 70,
        height: 50,
        alignment: Alignment.center,
        child: Text(name, style: _videoTypeStyle(type)),
      ),
      onTap: () {
        if (videoType != type) {
          setState(() {
            _results.clear();
            loading = true;
          });
          String path = "";
          if (type == 0) {
            path = "https://api.apiopen.top/todayVideo";
          } else {
            path = "https://api.apiopen.top/videoCategoryDetails?id=$id";
          }
          setState(() {
            videoType = type;
            videoPath = path;
            if (_dataList.containsKey(videoType)) {
              loading = false;
              _results = ToDayVideo.fromJson(_dataList[videoType]).result;
            } else {
              _getTodayVideo();
            }
          });
        }
      },
    );
  }

  //文字 style
  TextStyle _videoTypeStyle(int type) {
    if (videoType == type) {
      return TextStyle(
          fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white);
    } else {
      return TextStyle(
          fontSize: 14, fontWeight: FontWeight.normal, color: Colors.white70);
    }
  }

  //下拉刷新方法
  Future<Null> _refresh() async {
    _getTodayVideo();
    return null;
  }

  //item样式以及数据填充
  Widget _todayItem(Result item) {
    if (item.type == "FollowCard" || item.type == "followCard") {
      return Container(
        margin: EdgeInsets.all(5),
        padding: EdgeInsets.all(5),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(3)),
            color: _constant.getItemColor()),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  width: 30,
                  height: 30,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(15))),
                  child: ClipOval(
                    child: Image.network(item.data.content.data.provider.icon),
                  ),
                ),
                Expanded(
                  child: Text(item.data.content.data.provider.name),
                ),
                Text(DateTime.fromMicrosecondsSinceEpoch(
                        item.data.content.data.releaseTime * 1000,
                        isUtc: false)
                    .toIso8601String()
                    .substring(0, 16)
                    .replaceAll("T", " ")),
              ],
            ),
            Container(
              margin: EdgeInsets.only(top: 5, bottom: 5),
              child: Text(item.data.content.data.description),
            ),
            _videoPart(item),
          ],
        ),
      );
    } else {
      return Container(
        height: 0,
      );
    }
  }

  //视频部分处理
  Widget _videoPart(Result item) {
    if (playId == item.data.content.data.id) {
      _videoPlayerController =
          VideoPlayerController.network(item.data.content.data.playUrl);
      _chewieController = ChewieController(
          videoPlayerController: _videoPlayerController, autoPlay: true);
      return Container(
        alignment: Alignment.center,
        child: Chewie(
          controller: _chewieController,
        ),
      );
    } else {
      return Stack(
        children: <Widget>[
          _catchImage(item.data.content.data.cover.detail),
          Container(
            alignment: Alignment.center,
            child: IconButton(
                icon: Icon(
                  Icons.play_circle_filled,
                  size: 40,
                  color: Colors.white,
                ),
                onPressed: () {
                  setState(() {
                    playId = item.data.content.data.id;
                  });
                }),
          ),
        ],
        alignment: Alignment.center,
      );
    }
  }

  //获取视频信息
  void _getTodayVideo() async {
    var t = await Dio().get(videoPath).then((value) {
      try {
        ToDayVideo video = ToDayVideo.fromJson(value.data);
        print(video);
        //只有当前widget还在 tree中才设置值
        if (mounted) {
          setState(() {
            loading = false;
            _results = video.result;
          });
        }
        // ignore: unnecessary_statements
        _dataList.putIfAbsent(videoType, () => value.data);
      } catch (e) {
        //数据获取异常处理
      }
    });
  }

  //获取视频类型数据
  void _getVideoType() async {
    var t =
        await Dio().get("https://api.apiopen.top/videoCategory").then((value) {
      try {
        print(value);
        VideoType videoType = VideoType.fromJson(value.data);
        //只有当前widget还在 tree中才设置值
        if (mounted) {
          setState(() {
            _typeItems = videoType.result.itemList;
          });
        }
      } on DioError catch (e) {
        print(e);
      }
    });
  }

  Widget _catchImage(String url) {
    return CachedNetworkImage(
      imageUrl: url,
      placeholder: (context, str) {
        return Image.asset("images/ic_loading.gif");
      },
      errorWidget: (context, str, object) {
        return Image.asset("images/error.png");
      },
    );
  }
}
